package com.shbaiche.bifenba.ui.match;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.widget.EaseChatMessageList;
import com.hyphenate.exceptions.HyphenateException;
import com.sevenheaven.segmentcontrol.SegmentControl;
import com.shbaiche.bifenba.App;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.adapter.match.MatchBBSMessageListAdapter;
import com.shbaiche.bifenba.adapter.match.MatchListAdapter;
import com.shbaiche.bifenba.model.Event;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.data.CompeteVo;
import com.shbaiche.bifenba.model.match.EaseChatMessage;
import com.shbaiche.bifenba.model.match.EaseRegisterMessage;
import com.shbaiche.bifenba.model.match.MatchesListMessage;
import com.shbaiche.bifenba.model.match.MatchesVo;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.ui.base.BaseFragment;
import com.shbaiche.bifenba.ui.my.LoginActivity;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.SystemUtil;
import com.shbaiche.bifenba.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import cn.droidlover.xdroid.base.SimpleRecAdapter;
import cn.droidlover.xdroidbase.kit.Kits;
import cn.droidlover.xrecyclerview.RecyclerItemCallback;
import cn.droidlover.xrecyclerview.XRecyclerContentLayout;
import cn.droidlover.xrecyclerview.XRecyclerView;
import okhttp3.Call;

/**
 * 比赛详情-聊天室
 */

@SuppressLint("ValidFragment")
public class MatchDetailBBSFragment extends BaseFragment {
    @BindView(R.id.et_content)
    EditText etContent;

    @BindView(R.id.tv_send)
    TextView tvSend;

    @BindView(R.id.tv_num)
    TextView tvNum;

//    @BindView(R.id.layout_fragment)
//    RelativeLayout layoutFragment;



    @BindView(R.id.contentLayout)
    XRecyclerContentLayout contentLayout;

    private String mRoomId,mUserName;

    MatchBBSMessageListAdapter adapter;

    MatchesVo mMatchVo;

    EMMessageListener msgListener;

    EMChatRoomChangeListener roomChangeListener;

    private boolean isExit;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    listener(msg.obj.toString());
                    ToastUtil.show("加入聊天室成功");
                    break;
                case 1:
                    ToastUtil.show(msg.obj.toString());
                    break;
                case 2:
                    getMessageList();
                    break;

            }
        }
    };



    @SuppressLint("ValidFragment")
    public MatchDetailBBSFragment(){
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event.LoginEvent event) {
        if (event != null) {
            EMClient.getInstance().logout(true);
            register();
        }
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    public static MatchDetailBBSFragment newInstance() {
        return new MatchDetailBBSFragment();
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        isExit = false;
        if(savedInstanceState!=null && savedInstanceState.containsKey("data")){
            mMatchVo = (MatchesVo)savedInstanceState.getSerializable("data");
        }else{
            mMatchVo = (MatchesVo)getArguments().getSerializable("data");
        }

        initAdapter();
        register();

        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(App.getPassport()!=null){
                    String content = etContent.getText().toString();
                    if(!TextUtils.isEmpty(content)){
                        if(!TextUtils.isEmpty(mRoomId)){
                            //创建一条文本消息，content为消息文字内容，toChatUsername为对方用户或者群聊的id，后文皆是如此
                            EMMessage message = EMMessage.createTxtSendMessage(content, mRoomId);
                            //如果是群聊，设置chattype，默认是单聊

                            message.setChatType(EMMessage.ChatType.GroupChat);
                            //发送消息
                            EMClient.getInstance().chatManager().sendMessage(message);

                            getMessageList();

                            etContent.setText("");
                        }else{
                            ToastUtil.show("您还未加入群聊，请稍候。");
                        }
                    }else{
                        ToastUtil.show("发送内容不能为空");
                    }
                }else{
                    ToastUtil.show("请先登录");
                    LoginActivity.launch((Activity) context);
                }




            }
        });


    }



    private void initAdapter() {
        setLayoutManager(contentLayout.getRecyclerView());
        contentLayout.getRecyclerView()
                .setAdapter(getAdapter());
        contentLayout.getRecyclerView()
                .setOnRefreshAndLoadMoreListener(new XRecyclerView.OnRefreshAndLoadMoreListener() {
                    @Override
                    public void onRefresh() {
                        getMessageList();
                    }

                    @Override
                    public void onLoadMore(int page) {

                    }
                });

        contentLayout.loadingView(View.inflate(getContext(), R.layout.view_loading, null));
        //contentLayout.getRecyclerView().useDefLoadMoreView();
    }

    public void getRoomId() {
        EaseChatMessage message = new EaseChatMessage();
        message.setGameType(mMatchVo.getGameType());
        message.setGameId(mMatchVo.getGameId());
        message.setCompeteId(mMatchVo.getCompeteId());

        NetApi.easeChat(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                contentLayout.showContent();
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                contentLayout.showContent();
                ToastUtil.show("onFail" + e.getMessage());

            }

            @Override
            public void onResponse(TransMessage response, int id) {
                contentLayout.showContent();
                EaseChatMessage result =new Gson().fromJson(response.getMessage(),EaseChatMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null && result.getChatId()!=null){
                        Log.e("t","聊天室id: "+result.getChatId());
                        tvNum.setText(""+result.getNum());
                        joinRoom(result.getChatId());
                    }
                }else{
                    ToastUtil.show(response.getMessage());
                }
            }
        });

    }

    public void register() {
        EaseRegisterMessage message = new EaseRegisterMessage();
        message.setPassport(App.getPassport());
        message.setUniqueCode(SystemUtil.getUniquePsuedoID());

        NetApi.easeRegister(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                contentLayout.showContent();
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                contentLayout.showContent();
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onResponse(TransMessage response, int id) {
                contentLayout.showContent();
                EaseRegisterMessage result =new Gson().fromJson(response.getMessage(),EaseRegisterMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null && result.getUserName()!=null){
                        login(result.getUserName(),result.getPassword());
                    }
                }else{
                    ToastUtil.show(response.getMessage());
                }
            }
        });
    }



    private void login(final String userName, String password){
        try {
            EMClient.getInstance().login(userName,password,new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    Log.d("main", "登录聊天服务器成功！");
                    adapter.setUserName(userName);
                    mUserName = userName;
                    getRoomId();

                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
                    Log.d("main", "登录聊天服务器失败！"+message);

                    Message msg= new Message();
                    msg.what = 1;
                    msg.obj =  "登录聊天服务器失败！"+message;
                    handler.sendMessage(msg);

                }
            });
        }catch (Exception e){

        }catch (Error e){

        }

    }



    private void joinRoom(final String roomId){

        //roomId为聊天室ID
        EMClient.getInstance().chatroomManager().joinChatRoom(roomId, new EMValueCallBack<EMChatRoom>() {

            @Override
            public void onSuccess(EMChatRoom value) {
                //加入聊天室成功
                Log.e("t","加入聊天室成功");
                //listener(value.getName());
                mRoomId = roomId;
                Message msg= new Message();
                msg.what = 0;
                msg.obj = value.getId();
                handler.sendMessage(msg);

                //new出EaseChatFragment或其子类的实例
                EaseChatFragment chatFragment = new EaseChatFragment();
                //传入参数
                Bundle args = new Bundle();
                args.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
                args.putString(EaseConstant.EXTRA_USER_ID, mRoomId);
                chatFragment.setArguments(args);
                getChildFragmentManager().beginTransaction().add(R.id.layout_fragment, chatFragment).commit();
                getChildFragmentManager().beginTransaction().show(chatFragment).commit();

                EaseChatMessageList messageList = (EaseChatMessageList) getView().findViewById(R.id.message_list);
//初始化messagelist
                messageList.init(mRoomId, EaseConstant.CHATTYPE_GROUP, null);
//设置item里的控件的点击事件
                messageList.setItemClickListener(new EaseChatMessageList.MessageListItemClickListener() {

                    @Override
                    public void onUserAvatarClick(String username) {
                        //头像点击事件
                    }

                    @Override
                    public void onUserAvatarLongClick(String username) {

                    }

                    @Override
                    public void onMessageInProgress(EMMessage message) {

                    }

                    @Override
                    public boolean onResendClick(final EMMessage message) {
                        //重发消息按钮点击事件
                        return false;
                    }

                    @Override
                    public void onBubbleLongClick(EMMessage message) {
                        //气泡框长按事件
                    }

                    @Override
                    public boolean onBubbleClick(EMMessage message) {
                        //气泡框点击事件，EaseUI有默认实现这个事件，如果需要覆盖，return值要返回true
                        return false;
                    }
                });
//获取下拉刷新控件
                //swipeRefreshLayout = messageList.getSwipeRefreshLayout();
//刷新消息列表
                messageList.refresh();
                //messageList.refreshSeekTo(position);
                messageList.refreshSelectLast();

            }

            @Override
            public void onError(final int error, String errorMsg) {
                //加入聊天室失败
                Log.e("t","加入聊天室失败");

                Message msg= new Message();
                msg.what = 1;
                msg.obj = "加入聊天室失败";
                handler.sendMessage(msg);
            }
        });
    }

    private void getMessageList(){
        getMessageList(false);
    }

    private int lastSize = 0;

    private void getMessageList(boolean scroll){
        try{
            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(mRoomId,EMConversation.EMConversationType.ChatRoom);
            //EMConversation conversation = EMClient.getInstance().chatManager().getConversation(roomid);
            //获取此会话的所有消息
            if(conversation!=null){
                List<EMMessage> messages = conversation.getAllMessages();
                Log.e("t","历史记录："+messages.size()+"条");
                //Collections.reverse(messages);
                getAdapter().setData(messages);
                if(messages.size()!=lastSize){
                    lastSize = messages.size();
                    contentLayout.getRecyclerView().smoothScrollToPosition(getAdapter().getItemCount()-1);
                }

            }

        }catch (Exception e){

        }catch (Error error){

        }
        contentLayout.getSwipeRefreshLayout().setRefreshing(false);

    }



    private void listener(String roomid){

        getMessageList();

        //SDK初始化加载的聊天记录为20条，到顶时需要去DB里获取更多
        //获取startMsgId之前的pagesize条消息，此方法获取的messages SDK会自动存入到此会话中，APP中无需再次把获取到的messages添加到会话中
        //List<EMMessage> messages = conversation.loadMoreMsgFromDB(startMsgId, pagesize);

        msgListener = new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                //收到消息
                Log.e("t","收到消息");
                getMessageList();
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
                Log.e("t","收到透传消息");
                getMessageList();
            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
                //收到已读回执
                Log.e("t","收到已读回执");
            }

            @Override
            public void onMessageDelivered(List<EMMessage> message) {
                //收到已送达回执
                Log.e("t","收到已送达回执");
            }
            @Override
            public void onMessageRecalled(List<EMMessage> messages) {
                //消息被撤回
                Log.e("t","消息被撤回");
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
                Log.e("t","消息状态变动");
            }
        };

        roomChangeListener = new EMChatRoomChangeListener() {
            @Override
            public void onChatRoomDestroyed(String s, String s1) {
                Log.e("t","onChatRoomDestroyed");
            }

            @Override
            public void onMemberJoined(String s, String s1) {
                Log.e("t","onMemberJoined");
            }

            @Override
            public void onMemberExited(String s, String s1, String s2) {
                Log.e("t","onMemberExited");
            }

            @Override
            public void onRemovedFromChatRoom(int i, String s, String s1, String s2) {
                Log.e("t","onRemovedFromChatRoom");
            }

            @Override
            public void onMuteListAdded(String s, List<String> list, long l) {
                Log.e("t","onMuteListAdded");
            }

            @Override
            public void onMuteListRemoved(String s, List<String> list) {
                Log.e("t","onMuteListRemoved");
            }

            @Override
            public void onAdminAdded(String s, String s1) {
                Log.e("t","onAdminAdded");
            }

            @Override
            public void onAdminRemoved(String s, String s1) {
                Log.e("t","onAdminRemoved");
            }

            @Override
            public void onOwnerChanged(String s, String s1, String s2) {
                Log.e("t","onOwnerChanged动");
            }

            @Override
            public void onAnnouncementChanged(String s, String s1) {
                Log.e("t","onAnnouncementChanged");
            }
        };

        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(roomChangeListener);

        Log.e("t","开始监听：");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (!isExit){
                        Thread.sleep(1000 * 3);
                        handler.sendEmptyMessage(2);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onDestoryLazy() {
        super.onDestoryLazy();
        if(msgListener!=null){
            EMClient.getInstance().chatManager().removeMessageListener(msgListener);
        }
        if(roomChangeListener!=null){
            EMClient.getInstance().chatroomManager().removeChatRoomListener(roomChangeListener);
        }

        EMClient.getInstance().logout(true);

        isExit = true;
    }

    public SimpleRecAdapter getAdapter() {
        if (adapter == null) {
            adapter = new MatchBBSMessageListAdapter(getActivity());
            adapter.setRecItemClick(new RecyclerItemCallback<EMMessage, MatchBBSMessageListAdapter.ViewHolder>() {
                @Override
                public void onItemClick(int position, EMMessage model, int tag, MatchBBSMessageListAdapter.ViewHolder holder) {
                    super.onItemClick(position, model, tag, holder);
                }
            });
        }
        return adapter;
    }


    public void setLayoutManager(XRecyclerView recyclerView) {
        recyclerView.verticalLayoutManager(context);
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_match_detail_bbs;
    }
}
